package com.guaoran.source.rpc;

import com.guaoran.source.anno.RpcAnnotation;
import com.guaoran.source.curatorzk.IRegisterCenter;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * @author : 孤傲然
 * @Description :
 * @date :2018/6/13 15:07
 */
public class RpcRegisterServer {
    private final ExecutorService executors = Executors.newCachedThreadPool();
    //服务地址
    private String serviceAdress;
    //注册中心
    private IRegisterCenter registerCenter;
    //用来存放服务名称和服务对象之间的关系
    Map<String,Object> registerCenterMap = new HashMap<>();

    public RpcRegisterServer(String serviceAdress, IRegisterCenter registerCenter) {
        this.serviceAdress = serviceAdress;
        this.registerCenter = registerCenter;
    }

    /**
     * 绑定服务名称和服务对象
     * @param services
     */
    public void bind(Object... services){
        //根据注解获得实现对象的父类，定义为服务名称，
        for (Object service:services){
            RpcAnnotation annotation = service.getClass().getAnnotation(RpcAnnotation.class);
            String serviceName = annotation.value().getName();
            String version = annotation.version();
            if(version != null && !version.equals("")){
                serviceName += "-" + version;
            }
            registerCenterMap.put(serviceName,service);
        }
    }

    /**
     * 发布服务，进行监听客户端的请求,使用线程池进行处理请求
     */
    public void publisher(){
        ServerSocket serverSocket = null;
        try {
            String[] addrs = serviceAdress.split(":");

            //开启一个服务监听，
            serverSocket = new ServerSocket(Integer.parseInt(addrs[1]));
            System.out.println("服务端创建连接成功，正在监听客户端请求");
            //注册绑定的服务
            for (String interfaceName:registerCenterMap.keySet()) {
                registerCenter.register(interfaceName,serviceAdress);
                System.out.println("服务注册成功："+interfaceName+"-->"+serviceAdress);
            }
            while(true){
                Socket socket = serverSocket.accept();
                //使用线程去处理
                executors.execute(new ProcessThread(registerCenterMap,socket));
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

}
